﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxClasses;
using ITViet.Web.App_Code;
using ITViet.Domains;
using ITViet.Services;

namespace ITViet.Web.Admin
{
	public partial class ProductDetail : AdminBasePage
	{
		#region Properties
		private string m_innerError = string.Empty;
		private string m_checkBoxList = string.Empty;
		private string m_allIdList = string.Empty;

		internal override int RequiredPermission
		{
			get
			{
				return (int)FunctionList.Product;
			}
		}
		internal override void SetPermission()
		{
			if (!CanModify) btnSave.Visible = false;
		}

		#endregion

		#region Events
		protected void Page_Load(object sender, EventArgs e)
		{
			xdsLanguage.DataFile = XmlStatusFile;
			SettingUpload();
			if (!IsPostBack && !IsCallback)
			{
				cbxLanguage.Value = CurrentLanguage.Id;
				LoadLocale();
				LoadPhoto();
			}
		}

		protected void ctrlCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
		{
			string[] para = e.Parameter.Split('|');
			switch (para[0])
			{
				case "save":
					e.Result = "save|" + SaveProductInfo();
					break;
				case "language":
					e.Result = "language|" + ChangeLocale();
					break;
			}
		}

		protected void dvList_CustomCallback(object source, CallbackEventArgsBase e)
		{
			string[] para = e.Parameter.Split('|');
			switch (para[0])
			{
				case "Save":
					m_innerError = SavePhoto();
					break;
				case "Delete":
					m_innerError = DeletePhoto(para[1]);
					break;
			}
			LoadPhoto();
			if (m_innerError.Contains("OK"))
			{
				m_innerError += m_checkBoxList + "|" + m_allIdList;
			}
		}

		protected void dvList_CustomJSProperties(object sender, CustomJSPropertiesEventArgs e)
		{
			e.Properties["cpInnerError"] = m_innerError;
		}

		protected void dvList_DataBound(object sender, EventArgs e)
		{
			if (dvList.DataSource == null) return;
			hfCheckBoxList.Value = string.Empty;
			hfAllIdList.Value = string.Empty;
			m_allIdList = string.Empty;
			m_checkBoxList = string.Empty;
			for (int i = 0; i < dvList.Items.Count; i++)
			{
				HtmlInputCheckBox ckbox = dvList.FindItemControl("item_checkbox", dvList.Items[i]) as HtmlInputCheckBox;
				if (ckbox != null)
				{
					Multimedia photo = dvList.Items[i].DataItem as Multimedia;
					if (photo != null)
					{
						ckbox.Attributes.Add("onclick", "onSelect('" + photo.Id + "', this.checked)");
						hfAllIdList.Value += photo.Id + ",";
						m_allIdList += photo.Id + ",";
					}
					hfCheckBoxList.Value += ckbox.ClientID + ",";
					m_checkBoxList += ckbox.ClientID + ",";
				}
			}
		}
		#endregion

		#region Methods
		private void LoadLocale()
		{
			Product product = new ProductService().GetById(KeyId);
			if (product == null) return;
			ltrProductName.Text = product.Name;

			string whereclause = string.Format("ProductId = {0} AND LanguageId = {1}", KeyId, CurrentLanguage.Id);
			TList<ProductLocale> plList = new ProductLocaleService().Find(whereclause);
			if (plList.Count > 0)
			{
				txtName.Text = plList[0].Name;
				txtTags.Text = plList[0].Tags;
				txtPrice.Text = plList[0].RefPrice.ToString();
				txtGuaranty.Text = plList[0].GuarantyPeriod;
				txtMaterial.Text = plList[0].Material;
				txtOriginal.Text = plList[0].Original;
				mmSummary.Text = plList[0].Description;
				hdContent.Html = plList[0].Content;
			}
		}

		private string SaveProductInfo()
		{
			try
			{
				//Save locale
				ProductLocaleService productLocaleService = new ProductLocaleService();
				ProductLocale productLocale = null;
				int langid;
				int.TryParse(cbxLanguage.Value.ToString(), out langid);
				string whereclause = string.Format("ProductId = {0} AND LanguageId = {1}", KeyId, langid);
				TList<ProductLocale> productLocales = productLocaleService.Find(whereclause);
				productLocale = productLocales.Count > 0 ? productLocales[0] : new ProductLocale();
				productLocale.ProductId = KeyId;
				productLocale.LanguageId = langid;
				productLocale.Name = txtName.Text;
				decimal price = 0;
				decimal.TryParse(txtPrice.Text.Trim(), out price);
				productLocale.RefPrice = price;
				productLocale.GuarantyPeriod = txtGuaranty.Text;
				productLocale.Material = txtMaterial.Text;
				productLocale.Original = txtOriginal.Text;
				productLocale.Description = mmSummary.Text;
				productLocale.Content = hdContent.Html;
				productLocale.Tags = txtTags.Text;
				productLocaleService.Save(productLocale);
				//End Save locale

				return Resources.Messages.ERR0005;
			}
			catch (Exception ex)
			{
				WriteLog("", ex);
				return Resources.Messages.ERR0004;
			}
		}

		private string ChangeLocale()
		{
			int langid;
			int.TryParse(cbxLanguage.Value.ToString(), out langid);
			string whereclause = string.Format("ProductId = {0} AND LanguageId = {1}", KeyId, langid);
			TList<ProductLocale> productLocales = new ProductLocaleService().Find(whereclause);
			if (productLocales.Count > 0)
			{
				return string.Format("S|{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}",
					productLocales[0].Name, productLocales[0].RefPrice, productLocales[0].GuarantyPeriod, productLocales[0].Material, productLocales[0].Original, productLocales[0].Description, productLocales[0].Content, productLocales[0].Tags);
			}
			return "F|";
		}

		//***** Upload Photos
		private void SettingUpload()
		{
			MultiUpload1.FileType = AllowFileContentType.Image;
			MultiUpload1.UploadCompleteFunction = "UploadComplete";
			MultiUpload1.UploadSessionName = SessionName.UploadContainPostedFile;
			MultiUpload1.UploadFolder = FolderDirector.Photo;
			MultiUpload1.NoticeMessage = Resources.Messages.ERR0024;
		}

		private void LoadPhoto()
		{
			ProductService productService = new ProductService();
			Product product = productService.GetById(KeyId);
			if (product == null) return;
			if (product.AlbumId == null) return;
			TList<Multimedia> pList = new MultimediaService().GetByAlbumId(product.AlbumId);
			foreach (Multimedia photo in pList)
			{
				if (!string.IsNullOrEmpty(photo.Path))
				{
					photo.Path = "../" + photo.Path;
				}
			}
			dvList.DataSource = pList;
			dvList.DataBind();
		}

		private string SavePhoto()
		{
			try
			{
				ProductService productService = new ProductService();
				Product product = productService.GetById(KeyId);
				if (product != null)
				{
					if (product.AlbumId == null)
					{
						Album album = new Album();
						album.Name = product.Name;
						album.Type = AlbumType.Product;
						album.Status = VisibleStatus.Active;
						new AlbumService().Save(album);

						product.AlbumId = album.Id;
						productService.Save(product);
					}
					MultimediaService multimediaService = new MultimediaService();
					TList<Multimedia> pList = new TList<Multimedia>();
					string uploadedList = string.Empty;
					if (Session[SessionName.UploadReturnFiles] != null)
						uploadedList = Session[SessionName.UploadReturnFiles].ToString();

					if (!string.IsNullOrEmpty(uploadedList))
					{
						string[] fileList = uploadedList.Split(';');
						for (int i = 0; i < fileList.Length; i++)
						{
							if (string.IsNullOrEmpty(fileList[i])) continue;
							Multimedia photo = new Multimedia();
							photo.Path = fileList[i];
							photo.PostedBy = CurrentUser.Username;
							photo.PostedDate = DateTime.Now;

							photo.AlbumId = product.AlbumId;
							photo.Type = MultimediaType.Photo;
							photo.Status = VisibleStatus.Active;
							pList.Add(photo);
						}
					}
					ClearSession(new[] { SessionName.UploadReturnFiles, SessionName.UploadContainPostedFile });
					if (pList.Count > 0)
					{
						multimediaService.Save(pList);

						//Album album = new AlbumService().GetById(KeyId);
						return "SaveOK|";
					}
				}
			}
			catch (Exception ex)
			{
				WriteLog("PhotoList.aspx::Save Photo", ex);
				return Resources.Messages.ERR0004;
			}
			return string.Empty;
		}

		private string DeletePhoto(string deletedList)
		{
			try
			{
				if (!string.IsNullOrEmpty(deletedList))
				{
					MultimediaService pService = new MultimediaService();
					if (deletedList.EndsWith(","))
						deletedList = deletedList.Remove(deletedList.Length - 1);
					string[] idList = deletedList.Split(',');
					string[] imagePath = new string[idList.Length];
					for (int i = 0; i < idList.Length; i++)
					{
						if (string.IsNullOrEmpty(idList[i]))
							continue;
						int id = 0;
						int.TryParse(idList[i], out id);
						Multimedia photo = pService.GetById(id);
						if (photo != null)
						{
							string filePath = @MapPath("~\\" + photo.Path);
							imagePath[i] = filePath;
						}
					}
					pService.DeleteByIdList(deletedList);
					Album album = new AlbumService().GetById(KeyId);
				}
			}
			catch (Exception ex)
			{
				WriteLog("PhotoList.aspx::Delete Photo", ex);
				return Resources.Messages.ERR0004;
			}
			return "DeleteOK|";
		}
		//***** End Upload Photos
		#endregion
	}
}
